import asyncio
import time
import websockets
from datetime import datetime
import json

async def client():
    url = "ws://127.0.0.1:9824/register"
    print(datetime.now(), "开始连接",url)
    async with websockets.connect(url) as ws:
        print(datetime.now(), "连接成功")

        j = 0
        while True:
            if ws.open:
                if j % 115 == 0:
                    heart_data = {
                        "message_type": "heart",
                        "message_uuid": "uuid%d"%j,
                        "remark": "j=%d" % j
                    }
                    heart_data_message = json.dumps(heart_data)
                    print(datetime.now(),"c->s",heart_data_message)
                    await ws.send(heart_data_message)

                    print(datetime.now(), "s->c,j=%d, ws.recv start" % j)
                    response = await ws.recv()
                    print(datetime.now(), "s->c,j=%d, ws.recv end: " % j, response)

                if j % 1181 == 0 and j > 0:

                    pkt_data = {
                        "message_type": "clients",
                        "message_uuid": "uuid%d" % j
                    }
                    pkt_data_message = json.dumps(pkt_data)
                    print(datetime.now(),"c->s", pkt_data_message)
                    await ws.send(pkt_data_message)

                    print(datetime.now(), "s->c,j=%d, ws.recv start" % j)
                    response = await ws.recv()
                    print(datetime.now(), "s->c,j=%d, ws.recv end: " % j, response)

                j += 1
                await asyncio.sleep(0.001)
            else:
                print(datetime.now(), "websocket closed:j=%d" % j)
                break
    print(datetime.now(), "结束连接")


if __name__ == '__main__':
    # pip install websockets==13.1 -i https://pypi.tuna.tsinghua.edu.cn/simple
    asyncio.run(client())
